/****************************************************************************
**
** This file is part of the QtSerialPort module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "console.h"
#include "settingsdialog.h"
#include <QtCore/QDebug>
#include <QMessageBox>
#include <QLabel>
#include <QLineEdit>
#include <QtSerialPort/QSerialPort>
#include <QComboBox>
#include <QSpinBox>
#include "stare.h"
#include "pass.h"
#include "fall.h"
#include<QProgressBar>
//#include <AlignVCenter>
#include "opencv2/opencv.hpp"
#include<QTableWidget>
#include<QTime>

//#include "widget.h"
//#include "xyseriesiodevice.h"


#include <QtWidgets/QApplication>
#include <QtWidgets/QMainWindow>

#include <QtCharts/QChartView>
#include <QtCharts/QPieSeries>
#include <QtCharts/QPieSlice>
#include <QtWidgets>
#include <QtCharts>

#include"opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
//using namespace std;

/**
//include<iostream.h>
#include<stdio.h>
#include<cxcore.h>
#include<cvaux.h>
#include<highgui.h>
#include<cv.h>


#include <stdio.h>
#include <zbar.h>
#include <time.h>
#include <opencv/cv.h>
#include <iostream>
***/
#include <zbar.h>
#include <string.h>
using namespace cv;
using namespace std;
using namespace zbar;
//! [0]
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)

{
//! [0]
    ui->setupUi(this);
    console = new Console;
    setCentralWidget(console);
//! [1]
    serial = new QSerialPort(this);
//! [1]
    settings = new SettingsDialog;
    //Set    =   new Stare;
   // audio   =   new Widget;
    Pass_windos    =   new pass;
    Fass_windos    =   new fall;
    ui->actionConnect->setEnabled(true);
    ui->actionDisconnect->setEnabled(false);
    ui->actionQuit->setEnabled(true);
    ui->actionConfigure->setEnabled(true);
  //  ui->statusBar->setEnabled(false);
    progressBar =   new QProgressBar;
    //progressBar->setValue(30);//给进度条赋值
   // progressBar->setBackgroundRole(QColor(0,60,10));
    Message =   "SN:";
    status = new QLabel;
    sn_file = new QLabel;
    sn_file->setText(Message);
    linnumber   =   new QLineEdit;
    //linnumber   =   tr("SN");
    QFont font("ZYSong18030",12); //定义字体
    progressBar->setFont(font);//设置字体
    fass_chart=0.00;
    fall_chart=0.00;
    ui->statusBar->addWidget(status);
    ui->statusBar->addWidget(sn_file);
    ui->statusBar->addWidget(linnumber);
    ui->statusBar->addWidget(progressBar);
    initActionsConnections();
    connect(serial, static_cast<void (QSerialPort::*)(QSerialPort::SerialPortError)>(&QSerialPort::error),
            this, &MainWindow::handleError);

//! [2]
    connect(serial, &QSerialPort::readyRead, this, &MainWindow::readData);
//! [3]
    connect(settings, &SettingsDialog::new_pass, this, &MainWindow::new_fall);
//! [4]
    connect(console, &Console::New_pass, this, &MainWindow::PASS);
//! [5]
    connect(console, &Console::New_fall, this, &MainWindow::FALL);
//! [6]
    connect(console, &Console::New_pass_windos, this, &MainWindow::Fall_windos);
//! [7]
    connect(console, &Console::New_fall_windos, this, &MainWindow::Pass_Windos);
//! [8]
    connect(console, &Console::Progress, this, &MainWindow::ProgressBar);
//! [9]
    connect(settings, &SettingsDialog::Name_file_path, this, &MainWindow::name_file);
//! [10]
    connect(settings, &SettingsDialog::Sex_file_path, this, &MainWindow::sex_file);
//! [11]
    connect(settings, &SettingsDialog::Max_file_path, this, &MainWindow::max_file);
//! [12]
    connect(settings, &SettingsDialog::Min_file_path, this, &MainWindow::min_file);
//! [13]
    connect(settings, &SettingsDialog::Read_file_path, this, &MainWindow::read_file);
//! [14]
    connect(settings, &SettingsDialog::file_wire_Path, this, &MainWindow::new_file_Path);
//! [15]
    connect(settings, &SettingsDialog::send_wired, this, &MainWindow::new_fie_wried);
}
//! [16]
void    MainWindow::Fall_windos()
{
    Save();
    Pass_windos->pass_windos();
QApplication::restoreOverrideCursor();
}
//! [17]
void    MainWindow::Pass_Windos()
{
    Save();
    Fass_windos->fall_windos();
    QApplication::restoreOverrideCursor();
}
//! [18]
void    MainWindow::new_fall(int    pint)
{
    console->struct_Size(pint);
    RowCoun =   pint;
}
//! [19]
void    MainWindow::PASS(int    value)
{
    //Set->pass(value);
    fass_chart  =   value/number_chart;
    ui->actionTest->setEnabled(true);
}
//! [20]
void    MainWindow::FALL(int    dock)
{
    //Set->fall(dock);
    fall_chart  =   dock/number_chart;
    ui->actionTest->setEnabled(true);
}
//! [21]
MainWindow::~MainWindow()
{
    delete settings;
    //delete Set;
    delete Pass_windos;
    delete  Fass_windos;
    delete ui;
    //delete  chart_windos;


}

//! [22]
void MainWindow::openSerialPort()
{   t   =   0;
    SettingsDialog::Settings p = settings->settings();
    serial->setPortName(p.name);
    serial->setBaudRate(p.baudRate);
    serial->setDataBits(p.dataBits);
    serial->setParity(p.parity);
    serial->setStopBits(p.stopBits);
    serial->setFlowControl(p.flowControl);
    if (serial->open(QIODevice::ReadWrite))
    {
        console->setEnabled(true);
        console->setLocalEchoEnabled(p.localEchoEnabled);
        ui->actionConnect->setEnabled(false);
        ui->actionDisconnect->setEnabled(true);
        ui->actionConfigure->setEnabled(false);
        showStatusMessage(tr("Connected to %1 : %2, %3, %4, %5, %6")
                          .arg(p.name).arg(p.stringBaudRate).arg(p.stringDataBits)
                          .arg(p.stringParity).arg(p.stringStopBits).arg(p.stringFlowControl));


        ui->actionTest->setEnabled(true);


    } else
    {
        ui->actionTest->setEnabled(false);
        QMessageBox::critical(this, tr("Error"), serial->errorString());
        showStatusMessage(tr("Open error"));
    }


    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    //QApplication::restoreOverrideCursor()
    sleep(2000);
    QApplication::restoreOverrideCursor();


}
//! [23]
void MainWindow::closeSerialPort()
{
    if (serial->isOpen())
        serial->close();
    console->setEnabled(false);
    ui->actionConnect->setEnabled(true);
    ui->actionDisconnect->setEnabled(false);
    ui->actionConfigure->setEnabled(true);
    ui->actionTest->setEnabled(false);

    showStatusMessage(tr("Disconnected"));
}
//! [24]

void MainWindow::about()
{
    QMessageBox::about(this, tr("About Simple Terminal"),
                       tr("The <b>Simple Terminal</b> example demonstrates how to "
                          "use the Qt Serial Port module in modern GUI applications "
                          "using Qt, with a menu bar, toolbars, and a status bar."));
}

//! [25]
void MainWindow::writeData(const    QByteArray &data)
{
    serial->write(data);
    }

//! [26]
void MainWindow::readData()
{
    time    =   0;
//QFile   Data("../terminal/output.txt");
    QFile   Data(Read_File);
if(Data.open(QIODevice::WriteOnly|QIODevice::Append|QIODevice::Truncate))
  {
    while(time<8000)
{
    QByteArray data = serial->readAll();
    Data.write(data);
    time++;
    }
}
    Data.close();
    console->Txt_Data();
}
//![27]
void MainWindow::handleError(QSerialPort::SerialPortError error)
{
    if (error == QSerialPort::ResourceError) {
        QMessageBox::critical(this, tr("Critical Error"), serial->errorString());
        closeSerialPort();
    }
}
//! [28]

void MainWindow::initActionsConnections()
{
//! [29]
    connect(ui->actionConnect, &QAction::triggered, this, &MainWindow::openSerialPort);
//! [30]
    connect(ui->actionDisconnect, &QAction::triggered, this, &MainWindow::closeSerialPort);
//! [31]
    connect(ui->actionQuit, &QAction::triggered, this, &MainWindow::close);
//! [32]
    connect(ui->actionConfigure, &QAction::triggered, settings, &MainWindow::show);
//! [33]
    connect(ui->actionClear, &QAction::triggered, console, &Console::clear);
//! [34]
    connect(ui->actionAbout, &QAction::triggered, this, &MainWindow::about);
//! [35]
    connect(ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
//! [36]
    connect(ui->actionTest, &QAction::triggered, this, &MainWindow::Pass);
//! [37]
    connect(ui->Microphone, &QAction::triggered, this, &MainWindow::microphone);
//! [38]
  //  connect(ui->actionWebcam_test, &QAction::triggered, this, &MainWindow::Chart);
    connect(ui->actionWebcam_test, &QAction::triggered, this, &MainWindow::Chart);

}
//![39]
void MainWindow::showStatusMessage(const QString &message)
{
    status->setText(message);
    //linnumber->setText(message);
}
//![40]
void MainWindow::Pass()
{

    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
    ui->actionTest->setEnabled(false);
    linnumber->clear();
    progressBar->setValue(0);
    SN  =   Sn_number();
    linnumber->setText(SN);
    //Set->sn_fun(SN);
    SN  +=  ".txt";
    Save_Path =  SN_Number+SN;
    QFile   file(Save_Path);
    //file.close();
    file.resize(0);//
    QFile   Data(Read_File);//
    Data.resize(0);//clear Date zore
    console->clear();//clear date
    Fass_windos->close();//close pass windos
    Pass_windos->close();//close fall windos
    Path_fun(Save_Path);//save path
    QByteArray TMP=common;//send.....
    serial->write(TMP);

}
//! [41]
void MainWindow::name_file(QString   name)
{
    name_save   =   name;
    console->Name_file_read(name);
}
//! [42]
void MainWindow::sex_file(QString   sex)
{
    nsex_save   =   sex;
    console->Sex_file_read(sex);


}
//![43]
void MainWindow::max_file(QString   max)
{
    nmax_save   =   max;
    console->Max_file_read(max);


}
//![44]
void MainWindow::min_file(QString   min)
{
    nmin_save   =   min;
    console->Min_file_read(min);


}

//![45]
void MainWindow::read_file(QString   read_date)
{
    Read_File   =   read_date;
    console->Read_file_read(read_date);
}

//![46]
QString MainWindow::Sn_number()
{
    char    ss[20]="12iii3456";
    QString tm="11111111111111111111";
    QString sn_number  =   QString::fromLatin1(ss);
    return  sn_number;

}
//![47]
void MainWindow::new_file_Path(QString   new_file)
{
SN_Number   =   new_file;
}
//![48]
void MainWindow::Path_fun(QString    Save)
{
console->path_save(Save);
}
//![25]

void MainWindow::new_fie_wried(QString   new_file)
{
    common  =   new_file.toLatin1();
}


//![49]
void MainWindow::ProgressBar(int    Prog)
{
    progressBar->setValue(Prog+1);

}
/***
 *  function:open this file data save row data to "Save"funtion
 *  name:xianqi.zeng
 *  QT_versions:QT_V0
 *  QT_BEGIN_LICENSE:LGPL21
 * ***/

//![50]
void    MainWindow::Save()
{
    int i;
    QByteArray ename[RowCoun+1];
    QByteArray emax[RowCoun+1];
    QByteArray emin[RowCoun+1];
    QByteArray esex[RowCoun+1];
    QByteArray edata[RowCoun+1];


    QFile   save_name_file(name_save);
    if(!save_name_file.open(QIODevice::ReadOnly))
    {
       QMessageBox::about(NULL,"Test Simple Terminal ","<font color='red'>not  find /home/boot/terminal/name_list.txt</font");

    }
    QVector<QString>RowCount_name;
     while(!save_name_file.atEnd())
     {

         QString lineString_name=QString    (save_name_file.readLine()).trimmed();
         RowCount_name<<(i++,lineString_name);

     }
     for(int i  =   0;i <   RowCount_name.count();i++)
     {
         ename[i]   =   RowCount_name[i].toLatin1();

     }

   QFile   save_sex_file(nsex_save);
   if(!save_sex_file.open(QIODevice::ReadOnly))
   {
   QMessageBox::about(NULL,"Test Simple Terminal ","<font color='red'>not  find /home/boot/terminal/sex_list.txt</font");
   }
   QVector<QString>RowCount_sex;
while(!save_sex_file.atEnd())
{

   QString lineString_sex=QString    (save_sex_file.readLine()).trimmed();
   RowCount_sex<<(i++,lineString_sex);

}
for(int i   =   0;i <   RowCount_sex.count();i++)
{
   esex[i]=RowCount_sex[i].toLatin1();

}

   QFile   save_max_file(nmax_save);
   if(!save_max_file.open(QIODevice::ReadOnly))
   {
   QMessageBox::about(NULL,"Test Simple Terminal ","<font color='red'>not  find /home/boot/terminal/sex_list.txt</font");
   }
   QVector<QString>RowCount_max;
/***
 *  function:open this file data reada row data to "lineString_max"
 *  name:xianqi.zeng
 *  QT_versions:QT_V0
 *  QT_BEGIN_LICENSE:LGPL21
 * ***/
while(!save_max_file.atEnd())
{

   QString lineString_max=QString    (save_max_file.readLine()).trimmed();
   RowCount_max<<(i++,lineString_max);


}
for(int i   =   0;i <   RowCount_max.count();i++)
{
   emax[i]  =   RowCount_max[i].toLatin1();

}

   QFile   save_min_file(nmin_save);
   if(!save_min_file.open(QIODevice::ReadOnly))
   {
       QMessageBox::about(this, tr("About file open errer"),
                          tr("not path  min_list.txt"
                             "/home/boot/terminal/min_list.txt "
                             "file read errer"));
   }
   QVector<QString>RowCount_min;

while(!save_min_file.atEnd())
{

   QString lineString_min=QString    (save_min_file.readLine()).trimmed();
   RowCount_min<<(i++,lineString_min);
}
for(int i   =   0;i <   RowCount_min.count();i++)
{
   emin[i]  =   RowCount_min[i].toLatin1();
}
   QFile   save_test_file(Read_File);
   if(!save_test_file.open(QIODevice::ReadOnly))
   {
      QMessageBox::about(NULL,"Test Simple Terminal ","<font color='red'>not  find /home/boot/terminal/name_list.txt</font");
   }
QVector<QString>RowCount_TestData;
 while(!save_test_file.atEnd())
 {

     QString lineString_testdata=QString    (save_test_file.readLine()).trimmed();
     RowCount_TestData<<(i++,lineString_testdata);

 }
 for(int i  =   0;i <   RowCount_TestData.count();i++)
 {
     edata[i]   =   RowCount_TestData[i].toLatin1();

 }
/*****
 *  opencv file data save
 *  name:xianqizeng
 *  emal:---------
 * ****/
    QFile   DataSave(Save_Path);
    if(DataSave.open(QIODevice::WriteOnly|QIODevice::Append|QIODevice::Truncate))
      {
        /***
            header.append(QObject::tr("name"));
             header.append(QObject::tr("sex"));
             header.append(QObject::tr("min"));
                header.append(QObject::tr("max"));
            header.append(QObject::tr("val"));
            header.append(QObject::tr("test"));
          **/
        DataSave.write("name");
        DataSave.write("        ");
        DataSave.write("sex");
        DataSave.write("        ");
        DataSave.write("min");
        DataSave.write("        ");
        DataSave.write("max");
        DataSave.write("        ");
        DataSave.write("valu");
        DataSave.write("\n");



   for(int  j   =   0;j <   RowCoun;j++)
     {
    DataSave.write(ename[j]);
    DataSave.write("        ");
    DataSave.write(esex[j]);
    DataSave.write("        ");
    DataSave.write(emin[j]);
    DataSave.write("        ");
    DataSave.write(emax[j]);
    DataSave.write("        ");
    DataSave.write(edata[j]);
    DataSave.write("\n");
}
}
DataSave.close();   //fiel close
}
/****
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
**
*****/

//! [51]
void MainWindow::sleep(long    int msec)
{
    QTime   reachTime   =   QTime::currentTime().addMSecs(msec);
    while(QTime::currentTime()<reachTime)
    QCoreApplication::processEvents(QEventLoop::AllEvents,100);
}
/****
 *
 *
 *
 *
 * ***/
//! [52]
//! /**

void    MainWindow::Chart(void)
{
    chart_SN_pass   =   "pass "+QString::number(fass_chart)+"%";
    chart_SN_fall   =   "fall "+QString::number(fall_chart)+"%";
    QPieSeries *series = new QPieSeries();
    QPieSlice *slice_fall = series->append(chart_SN_fall, fall_chart);
    slice_fall->setExploded();
    slice_fall->setLabelVisible();
//![1]
    QPieSlice *slice_pass = series->append(chart_SN_pass, fass_chart);
    slice_pass->setExploded();
    slice_pass->setLabelVisible();
//![2]
    QChartView *chartView = new QChartView();
    chartView->setRenderHint(QPainter::Antialiasing);
    chartView->chart()->setTitle("Donut with a lemon glaze (100%)");
    chartView->chart()->addSeries(series);
    chartView->chart()->legend()->setAlignment(Qt::AlignBottom);
    chartView->chart()->setTheme(QChart::ChartThemeBlueCerulean);
    chartView->chart()->legend()->setFont(QFont("Arial", 12));
    chartView->resize(500,400);
    chartView->show();

}

//! [53]
//void MainWindow::microphone()
//{
 //   audio->resize(500,400);
   // audio->show();
 //}

//!
//!
//!
//!
void    MainWindow::microphone()
{/**
        IplImage* img = cvLoadImage("/home/boot/untitled1/char.png",-1);
        cvNamedWindow( "test", 0 );
        cvShowImage("test", img);
        cvWaitKey(0);
        cvReleaseImage( &img );
        cvDestroyWindow( "test" );
**/

/***

            CvCapture* pCapture = cvCreateCameraCapture(0);
           cvNamedWindow("Video", 1);
           while(1)
                 {
                     IplImage* pFrame=cvQueryFrame( pCapture );
                     if(!pFrame)break;
                     cvShowImage("Video",pFrame);
                     char c=cvWaitKey(33);
                     if(c==27)break;
                 }

           cvReleaseCapture(&pCapture);
                        cvDestroyWindow("Video");
***/
    Mat image;
    Mat glmage;

   ImageScanner scanner;
    scanner.set_config(ZBAR_NONE,ZBAR_CFG_ENABLE,1);
    char    Name[30];
    string  dat;
    char    temp[50];

    VideoCapture    cap(0);
    while(true)
    {
        cap>>image;
        cvtColor(image,glmage,CV_BGR2GRAY);
        int width=glmage.cols;
        int height=glmage.rows;

        uchar *data=(uchar*)glmage.data;
        //Image
        Image imageZbar(width,height,"Y800",data,width * height);
        scanner.scan(imageZbar);
        Image::SymbolIterator symbol = imageZbar.symbol_begin();

        for(;symbol != imageZbar.symbol_end();++symbol)
        {
            dat = symbol->get_type_name();
            dat = (string)Name;
            //cout<<"dat"<<Name<<endl;
            putText(image,symbol->get_type_name(),Point(30,30),1 ,1.0,Scalar(0,255,0));
            putText(image,symbol->get_data(),Point(30,60),1,1.0,Scalar(0,255,0));
            cout<<"类型："<<symbol->get_type_name()<<endl;
            cout<<"条码："<<symbol->get_data()<<endl;
            cout<<"dat"<<Name<<endl;
        }
        imshow("Soure Image",image);
        waitKey(1);
        imageZbar.set_data(NULL,0);

    //    cout<<"类型："<<endl<<symbol->get_type_name()<<endl<<endl;
      //  cout<<"条码："<<endl<<symbol->get_data()<<endl<<endl;
        //dat = symbol->get_type_name();
        //dat = (string)Name;
        //cout<<"dat"<<Name<<endl;
//
    }



}
/***
 *
 *	ImageScanner scanner;
    scanner.set_config(ZBAR_NONE,ZBAR_CFG_ENABLE,1);
    //Mat image = imread("code.jpg");
    char Name[30];
    string dat;
    char temp[50];
    VideoCapture cap(0);
    while(true)
    {
        cap>>image;
        cvtColor(image,gImage,CV_BGR2GRAY);
        int width = gImage.cols;
        int height = gImage.rows;
        uchar *data = (uchar*)gImage.data;
        Image imageZbar(width,height,"Y800",data,width * height);
        scanner.scan(imageZbar);
        Image::SymbolIterator symbol = imageZbar.symbol_begin();
        for(;symbol != imageZbar.symbol_end();++symbol)
        {
            //cout<<"类型："<<endl<<symbol->get_type_name()<<endl<<endl;
            //cout<<"条码："<<endl<<symbol->get_data()<<endl<<endl;
            //dat = symbol->get_type_name();
            //cout<<dat;
            //temp = dat.;
            //sprintf(Name,symbol->get_type_name());
            //dat = (string)Name;
            cout<<"dat"<<Name<<endl;
            putText(image,symbol->get_type_name(),Point(30,30),1 ,1.0,Scalar(0,255,0));
            putText(image,symbol->get_data(),Point(30,60),1,1.0,Scalar(0,255,0));
        }
        imshow("Soure Image",image);
        waitKey(1);
        imageZbar.set_data(NULL,0);
    }

 * libzbar.a      libzbargtk.so.0      libzbarqt.la        libzbar.so
libzbargtk.a   libzbargtk.so.0.0.2  libzbarqt.so        libzbar.so.0
libzbargtk.la  libzbar.la           libzbarqt.so.0      libzbar.so.0.2.0
libzbargtk.so  libzbarqt.a          libzbarqt.so.0.0.2
 *
 *
 *
 * ***/



